package at.jsug.topicvoting.gwt1.client.remote;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import at.jsug.topicvoting.gwt1.client.vo.Topic;

public class DummyDataFacade extends AbstractDataService {

	private static final DummyDataFacade INSTANCE = new DummyDataFacade();
	
	private final List<Topic> topics = new LinkedList<Topic>();
	
	
	private int idSequence = 0;
	
	private DummyDataFacade() {
		this.topics.add(Topic.newNeedTopic(idSequence++, "Ruby on Rails", 2, false));
		this.topics.add(Topic.newNeedTopic(idSequence++, "AspectJ", 4, true));
		this.topics.add(Topic.newNeedTopic(idSequence++, "PHP", 1, false));
		Collections.sort(this.topics);
	}
	
	public static DummyDataFacade getInstance() {
		return INSTANCE;
	}
	
	public List<Topic> getTopics() {
		return Collections.unmodifiableList(this.topics);
	}
	
	public void saveOrUpdateTopic(Topic topic) {
		final boolean isSaving = topic.getId() < 0;
		System.out.println("DummyData.saveOrUpdateTopic(); isSaving="+isSaving);
		
		if(isSaving == true) {
			
			// set proper id
			final Topic newTopic = Topic.newNeedTopic(idSequence++, topic.getTitle(), topic.getVotes(), topic.isYetVoted());
			this.topics.add(newTopic);
			
		} else { // update topic
			
			final Topic storedTopic = this.getTopicById(topic.getId());
			// assert(topic == storedTopic);
			final boolean removed = this.topics.remove(storedTopic);
			System.out.println("DummyData.updateTopic: removed == " + removed);
			// assert(removed == true);

			this.topics.add(topic);
		}
		
		Collections.sort(this.topics);
		this.broadcastDataChange();
	}
	
	private Topic getTopicById(long id) {
		// naive linear search
		for (Topic t : this.topics) {
			if(t.getId() == id) {
				return t;
			}
		}
		throw new RuntimeException("Could not get topic by id ["+id+"]!");
	}

	
	
}
